﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Z13qu.Code;
using Z13qu.Model;

namespace Z13qu.Service
{
    public class Sys_ModuleService : ServiceBase<Sys_Module>
    {
        Sys_RoleAuthorizeService roleAuthorizeService = new Sys_RoleAuthorizeService();
        public List<Sys_Module> GetList()
        {
            return IQueryable().OrderBy(t => t.SortCode).ToList();
        }

        public List<Sys_Module> GetMenuList(string roleId)
        {
            var data = new List<Sys_Module>();
            if (OperatorProvider.Provider.GetCurrent().IsSystem)
            {
                data = GetList();
            }
            else
            {
                var moduledata = GetList();
                var authorizedata = roleAuthorizeService.IQueryable(t => t.ObjectId == roleId && t.ItemType ==  ItemType.模块).ToList();
                foreach (var item in authorizedata)
                {
                    Sys_Module moduleEntity = moduledata.Find(t => t.Id == item.ItemId);
                    if (moduleEntity != null)
                    {
                        data.Add(moduleEntity);
                    }
                }
            }
            return data.OrderBy(t => t.SortCode).ToList();
        }

        public void DeleteById(string Id)
        {
            if (IQueryable().Count(t => t.ParentId.Equals(Id)) > 0)
            {
                throw new Exception("删除失败！操作的对象包含了下级数据。");
            }
            else
            {
                Delete(t => t.Id == Id);
            }
        }

        public void Submit(Sys_Module moduleEntity, string Id)
        {
            if (!string.IsNullOrEmpty(Id))
            {
                Update(moduleEntity);
            }
            else
            {
                Insert(moduleEntity);
            }
        }
    }
}
